var backgroundEntity;

$(document).ready(function() {

  Crafty.init(900,800).canvas.init();



  Crafty.c("BackgroundGrass",{
    init: function()
    {
      this.requires("2D, Canvas, Image").image("pic/grund13x13.png");
      this.attr({x:-200, y: -200, z: 1, w: 1300, h: 1300});

    }
  });

  Crafty.c("drawFPS", {
    init: function() {
      var d = new Date();
      var currentMilliseconds = d.getTime();
      $.data(document.body,"milliTime",currentMilliseconds);
      $.data(document.body,"trainSpeed", 0);  // PIXEL per Second
      $.data(document.body,"trainSpeedOverflow",0);
      $.data(document.body,"totalDistance",0);
      $.data(document.body,"backgroundPosCounter",0 );
      $.data(document.body,"curveCounter",0);
      $.data(document.body,"currentLokPos",0);

      this.bind("EnterFrame", function(){
        var currentMilliSeconds = $.data(document.body,"milliTime");
        var trainSpeed = $.data(document.body,"trainSpeed");
        var trainSpeedOverflow = $.data(document.body,"trainSpeedOverflow");
        var totalDistance = $.data(document.body, "totalDistance");

        var d = new Date();
        var now = d.getTime();
        var timeDif = now - currentMilliSeconds;

        $.data(document.body,"milliTime",now);

        var distance = trainSpeed * (timeDif / 1000 ) + trainSpeedOverflow ;  // pixel to move

        $.data(document.body,"trainSpeedOverflow", distance - Math.floor(distance));
        distance = Math.floor(distance);
        $.data(document.body, "totalDistance", totalDistance + distance);

        var currentLokPos = Math.floor((totalDistance / 100) +3);
        if($.data(document.body, "currentLokPos") < currentLokPos)
        {
          $.data(document.body, "currentLokPos",currentLokPos);
          if(ws != undefined && ws.readyState == 1)
          {
            ws.send('{"line_done": '+currentLokPos+'}');
          }
          console.log('{"line_done": '+currentLokPos+'}')
        }
        // check if we drive a curve


        if($.data(document.body,"curveModeLeft") == true)
        {
          var curveCounter = $.data(document.body,"curveCounter") + distance;
          var curve = Crafty("CurveObjectLeft");
          if(curve != undefined)
          {
            curve.origin(1300,1300);
            if(curve.y > -500 - (800-Crafty("SteamTrainLok").y) + 200)
            {
              // check if you want to drive the right side:
              if($.data(document.body,"nextDirection") != "left")
              {
                // now its game OVER ! just turn a little bit
                //$.data(document.body,"nextDirectionLock",true);
                //curve.origin(1300,1300);
                //curve.rotation = Math.floor((curveCounter / 450) * 90);

                //if(curve.rotation <= - 40)
                //{
                  ws.send('{"gameover": true}');
                  $.data(document.body,"nextDirection",null);
                //}

                $.data(document.body,"curveCounter",curveCounter);
              } else {
                // Everythink ok :)
                //console.log((curveCounter / 450) * 90);
                // nach 450pixel muss der Zug gedreht sein
                curve.rotation = Math.floor((curveCounter / 450) * 90);
                $.data(document.body,"curveCounter",curveCounter);
              }
            }
          }
          if(curveCounter > 450 )
          {
            curve.destroy();
            $.data(document.body,"curveModeLeft",false);
            $.data(document.body,"curveCounter",0);
          }
        }
        else if($.data(document.body,"curveModeRight") == true)
        {
          var curveCounter = $.data(document.body,"curveCounter") + distance;
          var curve = Crafty("CurveObjectRight");
          if(curve != undefined)
          {
            curve.origin(1300,1300);
            if(curve.y > -500 - (800-Crafty("SteamTrainLok").y) + 200)
            {

              // check if you want to drive the right side:
              if($.data(document.body,"nextDirection") != "right")
              {
                // now its game OVER ! just turn a little bit
                //$.data(document.body,"nextDirectionLock",true);
                //curve.origin(0,1300);
                //curve.rotation = - Math.floor((curveCounter / 450) * 90);
                //$.data(document.body,"curveCounter",curveCounter);

                //if(curve.rotation >= 40)
                //{
                  ws.send('{"gameover": true}');
                  $.data(document.body,"nextDirection",null);
                //}
                $.data(document.body,"curveCounter",curveCounter);
              } else {
                // Everythink ok :)
                curve.rotation = - Math.floor((curveCounter / 450) * 90);
                $.data(document.body,"curveCounter",curveCounter);
              }

            }
          }
          if(curveCounter > 450 )
          {
            curve.destroy();
            $.data(document.body,"curveModeRight",false);
            $.data(document.body,"curveCounter",0);
          }
        }



        //console.log(objToMove);
        // move Backgrounds
        if(backgroundEntity.y > -100 )
        {
          // jump!
          backgroundEntity.y -= 100 - distance;
        } else {
          backgroundEntity.y += distance;
        }

        // Move Objects
        var objsToMove = Crafty("LineObject");
        for(var i=0; i< objsToMove.length; i++)
        {
          var obj = Crafty(objsToMove[i]);
          var y = obj.y;
          var newy = y + distance;
          if((newy) > 1000 )
          {
            obj.destroy();
          }
          else
          {
            obj.y += distance
          }
        }
        // now Move background
        //console.log(Crafty("BackgroundLayer"));
      });
    }
  });

  Crafty.scene("loading", function() {

    console.log(allTextures);
    // Load our assets
    Crafty.load(allTextures, function() {
      // Put in a fake timeout so we can see this in action

      Crafty.scene("main"); // Play the main scene
      Crafty.background("#ffa500");

    },
    function(e) {
      console.log(e);
    },

    function(e) {
      console.log(e);
    }

    );

    // White background and some ugle text
    Crafty.background("#FFF");
    Crafty.e("2D, Canvas, Text").attr({w: 640, h: 20, x: 0, y: 120})
        .text("Loading");

  });

  Crafty.scene("main",function()
  {
    //Crafty.background(" url('pic/gras100.png') ");
    var fps = Crafty.e("drawFPS");
    Crafty.background("#FFF");
    console.log('Hello My Friend');
    $.data(document.body, "currentLine", 0);

    backgroundEntity = Crafty.e("BackgroundGrass");

    var train = Crafty.e("SteamTrainLok");
    var wagon = Crafty.e("SteamTrainWagon");

    // Add grass texture
    startWebSocket();




  });

  Crafty.scene("loading");




});
